package com.ts.api.module.api.convert.market.handler;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.encode.HexUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.exp.ChannelMarketParamException;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.handler.ApiConsumerConvertHandler;
import com.ts.api.module.api.convert.market.entity.ChannelMarketParameter;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 *  渠道上游产品(贷超)接入接口
 */
public interface ChannelMarketConvertHandler extends ApiConsumerConvertHandler {

    /**
     *  解析参数
     *
     *  @param  requestVO
     *  @return ApiUserInfo
     */
    ApiUserRequest parse(RequestVO requestVO);

    /**
     *  响应请求
     *
     *  @param  channelMarketParameter      返回时需要用到的业务数据
     *  @param  apiBizStatus                API业务状态
     *  @return Map
     */
    Map<String, Object> response(ChannelMarketParameter channelMarketParameter, ApiBizStatus apiBizStatus);

    /**
     *  渠道上游产品解密方法
     *
     *  @return Map
     *  @param  <T>  ApiUserInfo父类
     *  @return Map
     */
    default ApiUserRequest decrypt(RequestVO requestVO) {
        String secret = "8cf70e3cf21ab7c1bca151943e6b2df80ba6a8d9b217940ac6c6b53ca8d6ea5e";

        String body = requestVO.getBody();
        if (ValidParam.isEmpty(body)) {
            throw new ChannelMarketParamException("非法请求体");
        }

        JSONObject dataJson = JsonUtils.get(body);
        String dataValue = dataJson.getString("data");
        if (ValidParam.isEmpty(dataValue)) {
            throw new ChannelMarketParamException("请求值为空");
        }

        AES ecb = AES.createEcb(HexUtils.decode(secret));
        try {
            String decryptValue = ecb.decryptFromHexStr(dataValue);
            return JsonUtils.toBean(decryptValue, ApiUserRequest.class);
        } catch (Exception e) {
            throw new ChannelMarketParamException("解密失败");
        }
    }
}
